Avoid no-op EC KV reads in post-send pull sync - #900
Conversation
0532bba to
41544e8
Compare
prk-Jr
left a comment
There was a problem hiding this comment.
Summary
Solid, well-scoped implementation of the #880 contract: the marker protocol is cryptographically careful, the preload gate enumerates its consumers explicitly instead of guessing, and the fallbacks all fail toward the KV path. One blocking issue: the withdrawal path emits the marker-expiry Set-Cookie unconditionally, which downgrades cache privacy for an entire traffic class that previously had no Set-Cookie at all.
2 of the inline comments below carry a one-click GitHub
suggestion— use Commit suggestion (or Add suggestion to batch) to apply them as commits on the PR branch. Both were applied in an isolated worktree at this head and verified withcargo fmt --all -- --check,cargo clippy-fastly,cargo check-axum,cargo check-cloudflare, and the nativetrusted-server-coreec::+ publisher marker tests (332 and 28 passing respectively), with a byte-exact pre/post drift check. The remaining comments describe the fix in prose because it spans two files.
Blocking
🔧 wrench
- Withdrawal always emits a marker-expiry
Set-Cookie, downgrading cache privacy for all withdrawn traffic — see inline atcrates/trusted-server-core/src/ec/finalize.rs:63
Non-blocking
🤔 thinking
- Marker issuance re-adds a
Set-Cookieto responses PR #885 deliberately made cookie-free — see inline atcrates/trusted-server-core/src/ec/finalize.rs:160
♻️ refactor
- Completeness duplicates dispatch eligibility; the two can drift — see inline at
crates/trusted-server-core/src/ec/pull_sync_marker.rs:170
⛏ nitpick
- The three-state loop asserts the same thing three times — see inline at
crates/trusted-server-adapter-fastly/src/main.rs:553
👍 praise
- Marker crypto and framing — see inline at
crates/trusted-server-core/src/ec/pull_sync_marker.rs:299
Cross-cutting / body-level findings
- 📝 Verified as correct, for the record — several things that look risky on first read hold up: the
expectinreconcile_markeris unreachable because thebelongs_tocheck precedes thePresentmatch andentry_forignoresgeneration; the partner-set fingerprint is consistent across the validate and issue sites because every caller builds the registry fromPartnerRegistry::from_config(&settings.ec.partners);upsert_partner_ids_from_snapshotreturns early on empty updates, so a marker-valid navigation really does perform zero reads rather than moving the read later; stored KV EIDs reach only the auction path, whichauction_needs_rowforces the read for; tombstones are excluded viaconsent.ok; and per-partnerpull_sync_ttl_secis not wired into eligibility, so presence-only completeness matches dispatch today (see the ♻️ finding for the drift risk that creates).
CI Status
- cargo fmt: PASS
- cargo test: PASS
- cargo test (axum native): PASS
- cargo test (cloudflare native + wasm32-unknown-unknown): PASS
- cargo check (cloudflare native + wasm32-unknown-unknown): PASS
- cargo check/build/test (spin native + wasm32-wasip1): PASS
- cargo test (cross-adapter parity): PASS
- cargo test (ts CLI, native): PASS
- vitest: PASS
- format-typescript: PASS
- format-docs: PASS
- prepare integration artifacts: PASS
- integration tests: PASS
- integration tests (Fastly EC lifecycle): PASS
- browser integration tests: PASS
All 14 reported checks pass. gh pr checks --required returned no names for this PR, so no check is annotated as branch-protection-required (the base branch is fix/kv-eid-request-snapshot-ec-ttl, not main).
|
@ChristianPavilonis please assign issue for this PR |
prk-Jr
left a comment
There was a problem hiding this comment.
Summary
Adds a signed, host-only browser marker that lets an eligible navigation skip the EC identity-graph read when pull-sync completeness is the only reason to inspect the row, and returns from post-send pull sync before the graph is constructed when there is nothing to pull. The design is sound and the skip is well fenced: I traced each path rather than only reading the diff.
4 of the inline comments below carry a one-click GitHub
suggestion— use Commit suggestion (or Add suggestion to batch for several at once) to apply them as commits on the PR branch. All four were applied and verified in an isolated worktree at963c331(cargo fmt --all -- --check,cargo clippy-fastly,cargo check-fastly, andcargo test -p trusted-server-core --lib ec::— 334 passed), individually and as a batch, with a byte-exact pre/post drift check.
What I verified beyond the diff
marker_validimplies a non-empty registry.partner_set_fingerprintreturnsNonefor an empty pull set, so a valid marker requires at least one pull-enabled partner, soauction_needs_row == should_run_auction. A marker skip can therefore never suppress a read the auction needs.- A generated EC never carries a valid marker.
generate_if_neededandreplace_with_generatedboth callinvalidate_for_replaced_ec(), so the generated-cookie path atec/finalize.rs:150always has a real snapshot. No phantom-cookie regression fromentry_for(&ec_id).is_none(). - The EID gate matches its consumer exactly.
collect_eid_cookie_updatesreads onlyts-eidsandsharedId— the same two constantseid_cookie_may_need_persistencechecks — andupsert_partner_ids_from_snapshotshort-circuits on empty updates, so aNotReadsnapshot costs no hidden read in finalize. - No shared-cache leak from the new
Set-Cookie.enforce_set_cookie_cache_privacyruns inapply_terminal_response_effects, i.e. afterec_finalize_response, and the template cache stores reader-neutral bytes rather than response headers. - The
expect()inreconcile_markercannot fire. The!belongs_to(ec_id)early return plus thePresentmatch arm together guaranteeentry_forisSome. reconcile_markerruns exactly once per finalize call. Every branch either returns before it or falls through to a single call, so no response can pick up a duplicate markerSet-Cookie.- Only the Fastly adapter calls
build_pull_sync_context; the Cloudflare, Spin, and Axum adapters are unaffected by the signature change.
Non-blocking
♻️ refactor
build_pull_sync_contextdoc no longer describes its return contract — see inline atcrates/trusted-server-core/src/ec/pull_sync.rs:60entry_is_pull_completedoc omits the consent and empty-registry conditions — see inline atcrates/trusted-server-core/src/ec/pull_sync.rs:285
🤔 thinking
- No test for the two "steady state implies no
Set-Cookie" invariants — see inline atcrates/trusted-server-core/src/ec/pull_sync_marker.rs:580 should_preload_ecis double-duty and its safety argument is implicit — see inline atcrates/trusted-server-core/src/publisher.rs:4411
Cross-cutting / body-level findings
-
🤔
prepare_pull_sync_after_send's test asserts a property that already held —crates/trusted-server-adapter-fastly/src/main.rs:553.pull_sync_noop_states_skip_post_send_graph_factoryproves that aNoneplan does not build the graph, but the pre-PR shape (if is_real_browser && let Some(context) = build_pull_sync_context(..)wrappingrun_pull_sync_after_send, which built the graph inside) already guaranteed that. The behaviour that actually changed —build_pull_sync_contextreturningNonefor a complete row or an empty pull registry — is covered bybuild_pull_sync_context_skips_empty_registry_and_complete_snapshot. The case this helper uniquely adds and does not cover isSome(context)with a failinggraph_factory. Worth either covering that arm or noting that the helper exists purely to make the ordering testable. -
🌱 Allocation churn on the finalize path —
sorted_pull_partner_domainsclones everysource_domainString, and a singlereconcile_markerwalks it twice on the issue path (once directly, once throughcreate_marker->partner_set_fingerprint), withentry_is_pull_completecallingpull_enabled_partners()again. That is three to four partner-set traversals per response in Wasm, where CLAUDE.md asks to minimise allocations. Small in absolute terms and it does not belong in this PR, but a cached fingerprint onPartnerRegistrywould remove all of it. Follow-up. -
📝 Orphan-recovery detection is deferred by up to
MARKER_MAX_AGE_SECS— a marker-skipped navigation never observes aMissingsnapshot, sorecovery_eligiblecannot fire until the marker expires. This is explicitly accepted in the plan doc anddocs/guide/edge-cookies.md; recording it here so the tradeoff is visible on the PR thread rather than only in the plan. -
👍 The crypto hygiene here is genuinely good. Key separation through
MARKER_KEY_LABELrather than usingec.passphraseas the HMAC key directly; length-prefixed domain hashing inpartner_set_fingerprint, which removes the concatenation ambiguity a naive join would introduce; constant-timeverify_slicefor the tag; a both-sided expiry window (expires_at <= nowandexpires_at > now + MARKER_MAX_AGE_SECS) so a forged far-future expiry is rejected; andRedactedplus a hand-writtenDebugso the marker cannot leak into logs.EcSnapshotPreloadInputnaming all four "another consumer needs the row" guards is the right call too — it turns an implicit condition into something reviewable.
CI Status
cargo fmt: PASScargo test: PASScargo test (axum native): PASScargo test (cross-adapter parity): PASScargo test (ts CLI, native): PASScargo check (cloudflare native + wasm32-unknown-unknown): PASScargo check/build/test (spin native + wasm32-wasip1): PASSintegration tests: PASSintegration tests (Fastly EC lifecycle): PASSbrowser integration tests: PASSprepare integration artifacts: PASSvitest: PASSformat-typescript: PASSformat-docs: PASS
No check reported as required by branch protection on this branch; all 14 reported checks pass.
963c331 to
4e9a01e
Compare
4e9a01e to
4bd7ada
Compare
aram356
left a comment
There was a problem hiding this comment.
Summary
Adds a signed, one-hour browser marker asserting that the EC row already holds every pull-partner UID, and uses it to skip the KV snapshot preload and the post-send identity-graph construction. The cryptographic construction is solid — a proper two-level HMAC KDF with domain separation, constant-time tag verification, length-prefixed fingerprint hashing, a host-only Secure/HttpOnly cookie, and every rejection path failing closed into a full KV read. I found no forgery, replay, or injection vector.
The blocking findings are about behavior and payoff rather than crypto: orphan recovery stops firing on the skip path (a regression against main, and one the PR description says is preserved), and the auction_needs_row hatch cancels the skip on exactly the ad-serving navigations the change targets. Both were verified with scratch tests in a worktree at this head, not by inspection alone.
None of the inline comments below carry a one-click
suggestion. Scratch verification demoted both suggestion candidates to prose: the clock-skew fix breaks an existing assertion in a different range, and the cookie-bound fix needs a shared constant that lives outside the hunk. Each comment gives the proposed code in a plain block to apply manually.
Blocking
🔧 wrench
- Orphan recovery silently stops firing on the marker-skip path — see inline at
crates/trusted-server-core/src/ec/finalize.rs:97 - The optimization does not fire on ad-serving navigations — see inline at
crates/trusted-server-core/src/publisher.rs:4417
❓ question
- What is the measured KV-read reduction in production? — see Cross-cutting below
Non-blocking
🤔 thinking / ♻️ refactor / ⛏ nitpick
- Zero clock-skew tolerance on the marker expiry upper bound — see inline at
crates/trusted-server-core/src/ec/pull_sync_marker.rs:263 - Host-only cookie scope is an unstated security invariant — see inline at
crates/trusted-server-core/src/ec/pull_sync_marker.rs:196 - Marker cookie is stored unvalidated at the parse site — see inline at
crates/trusted-server-core/src/ec/mod.rs:181 snapshot_already_readis constant-false at the call site — see inline atcrates/trusted-server-core/src/publisher.rs:4424
Cross-cutting / body-level findings
-
❓ What is the measured KV-read reduction in production? — Findings 1 and 2 together mean the change trades an orphan-recovery regression for a benefit that, in the tests as written, only materialises on navigations with no matched ad slots. Before merging ~1,100 lines and a new signed browser cookie, could you share the measured before/after KV read counts on real traffic?
Note that the pull-sync half of this PR stands on its own and looks right independently: the
entry_is_pull_completeshort-circuit inbuild_pull_sync_context(crates/trusted-server-core/src/ec/pull_sync.rs:76-81) plusprepare_pull_sync_after_send(crates/trusted-server-adapter-fastly/src/main.rs:355) already skip the post-send graph construction when there is nothing to pull, with no cookie, no HMAC, and no snapshot-skip involved. If the marker's measured win is small, closing #880 with just that part would avoid both blocking findings entirely. -
📝 Verification performed for this review — Ran in a clean worktree at
4bd7adad:cargo fmt --all -- --check(clean),cargo clippy-fastly,cargo clippy-axum,cargo test-axum(26 passed),cargo test -p trusted-server-core --lib(2687 passed). Two scratch reproductions confirmed findings 1 and 2; both were reverted and the worktree restored to the PR head. -
📝 Angles checked and cleared — For the record, these were investigated and found sound, so they need no action: the
expect()atpull_sync_marker.rs:135is provably unreachable (the guards at lines 121 and 126 makeentry_fortotal on that arm); the threeHmacSha256::new_from_slice(...).expect(...)calls cannot fail (HMAC accepts any key length, and a ≥32-character passphrase is separately enforced at config load insettings.rs:611-631); the\0-separated marker payload is not ambiguous becauseec_idisis_valid_ec_id-filtered before it reachesec_value; the non-constant-time fingerprint comparison beforeverify_sliceleaks only a public config digest, not keying material; no new dependencies were added (hex,hmac,sha2were already present); and the doc's cache-privacy claim is accurate —enforce_set_cookie_cache_privacydoes downgrade anySet-Cookie-bearing response.
CI Status
- cargo fmt: PASS (required)
- cargo test: PASS (required)
- format-typescript: PASS (required)
- format-docs: PASS (required)
- cargo test (axum native): PASS
- cargo test (cloudflare native + wasm32-unknown-unknown) / cargo check: PASS
- cargo check/build/test (spin native + wasm32-wasip1): PASS
- cargo test (cross-adapter parity): PASS
- cargo test (ts CLI, native): PASS
- vitest: PASS
- prepare integration artifacts: PASS
- Analyze (javascript-typescript): PASS
- Analyze (actions): PASS
- Analyze (rust): PENDING
- integration tests: PENDING
- integration tests (Fastly EC lifecycle): PENDING
- browser integration tests: PENDING
- CodeQL: SKIPPED
No failing checks at review time.
Summary
This PR builds on #885, which is now in
main. The zero-operation guarantee is scoped to KV work caused solely by pull sync; other identity lifecycle consumers may still require the shared EC snapshot. A valid marker acts as recent existence proof, so deletion of a previously complete row is detected after marker expiry rather than on every marked request.Changes
crates/trusted-server-core/src/ec/pull_sync_marker.rscrates/trusted-server-core/src/ec/{mod,finalize,pull_sync}.rscrates/trusted-server-core/src/publisher.rscrates/trusted-server-adapter-fastly/src/main.rsdocs/guide/edge-cookies.mddocs/superpowers/plans/2026-07-13-issue-880-no-op-pull-sync-kv-reads.mdCloses
Closes #880
Test plan
cargo test-fastly && cargo test-axumcargo clippy-fastly && cargo clippy-axumcargo fmt --all -- --checkcd crates/trusted-server-js/lib && npx vitest runcd crates/trusted-server-js/lib && npm run formatcd docs && npm run formatcargo build --package trusted-server-adapter-fastly --release --target wasm32-wasip1fastly compute serve— not runcargo test-cloudflare,cargo test-spin, cross-adapter parity, and all Cloudflare/Spin native + WASM clippy targetsChecklist
unwrap()in production code — useexpect("should ...")logmacros (notprintln!)